package org.jash.ting13.home

import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import androidx.core.view.children
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.OrientationHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import com.google.android.material.carousel.CarouselLayoutManager
import com.google.android.material.carousel.CarouselSnapHelper
import com.google.android.material.carousel.FullScreenCarouselStrategy
import org.jash.ting13.BR
import org.jash.ting13.R
import org.jash.ting13.entity.SliderEntity
import org.jash.utils.CommonAdapter
import org.jash.utils.log

@BindingAdapter("adapter")
fun setBannerAdapter(banner: RecyclerView, data:List<SliderEntity>) {
    if (banner.adapter == null) {
        banner.layoutManager = CarouselLayoutManager(FullScreenCarouselStrategy(), CarouselLayoutManager.HORIZONTAL)
        banner.adapter = CommonAdapter({ R.layout.item_slider to BR.slider}, data.toMutableList())
        val helper = CarouselSnapHelper()
        helper.attachToRecyclerView(banner)
    }
}
@BindingAdapter("autoplay")
fun autoplay(recycler: RecyclerView, time:Int) {
    val action = object :Runnable {
        override fun run() {
            val view = recycler.children.first { it.x == 0f }
            var i = recycler.getChildAdapterPosition(view) + 1
            if (i == recycler.adapter?.itemCount) {
                i = 0
            }
            recycler.smoothScrollToPosition(i)
            recycler.postDelayed(this, time.toLong())
        }
    }
    recycler.postDelayed(action, time.toLong())
    recycler.addOnScrollListener(object : OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            when(newState) {
                SCROLL_STATE_IDLE -> recyclerView.postDelayed(action, time.toLong())
                else -> recyclerView.removeCallbacks(action)
            }
        }
    })
}